﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.Models;
using JiveMessenger.Utilities;
using NLog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;

namespace JiveMessenger.ViewModels
{
    public class ViewModelLogsWindow : ViewModelBase
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private string _logFolder;
        public RelayCommand<LogFileModel> OpenLogFileCommand { get; set; }
        public RelayCommand<LogFileModel> DeleteLogFileCommand { get; set; }

        private ObservableCollection<LogFileModel> _files;
        public ObservableCollection<LogFileModel> LogFiles
        {
            get { return _files; }
            set
            {
                if (_files != value)
                {
                    Set(() => LogFiles, ref _files, value);
                }
            }
        }

        public ViewModelLogsWindow(string folder)
        {
            this._logFolder = folder;
            DirectoryInfo di = new DirectoryInfo(this._logFolder);
            if (!di.Exists)
                return;

            this.LogFiles = new ObservableCollection<LogFileModel>(di.GetFiles("*.xml", SearchOption.TopDirectoryOnly).Select(x => new LogFileModel(x)).OrderByDescending(x => x.LastWriteTime));

            this.OpenLogFileCommand = new RelayCommand<LogFileModel>(OpenLogFileCommandAction);
            this.DeleteLogFileCommand = new RelayCommand<LogFileModel>(DeleteLogFileCommandAction);
        }
        public ViewModelLogsWindow() { }
        private void DeleteLogFileCommandAction(LogFileModel log)
        {
            Messenger.Default.Send(new NotificationMessageAction<MessageBoxResult>(this, string.Format("Are you sure you want to delete {0}?", log.FileName), "QueryDeleteFile", result =>
                {
                    if (result == MessageBoxResult.OK || result == MessageBoxResult.Yes)
                    {
                        try
                        {
                            File.Delete(log.File.FullName);
                            this.LogFiles.Remove(log);
                        }
                        catch (Exception err)
                        {
                            Messenger.Default.Send<string>(String.Format("Could not delete the file {0}: {1}.", log.File.FullName, err.Message));
                            Logger.ErrorException(String.Format("Could not delete the file {0}", log.File.FullName), err);
                        }
                    }
                }));
        }

        private void OpenLogFileCommandAction(LogFileModel log)
        {
            if (File.Exists(log.File.FullName))
            {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo = new System.Diagnostics.ProcessStartInfo(log.File.FullName);
                p.StartInfo.Verb = "Open";
                p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                bool started = p.Start();
                if (!started)
                    Logger.Error("Could not open log file");
                try
                {
                    int procId = p.Id;
                }
                catch (InvalidOperationException ex)
                {
                    started = false;
                    Logger.ErrorException("Error opening log file", ex);
                }
                catch (Exception ex)
                {
                    started = false;
                    Logger.ErrorException("Error opening log file", ex);
                }
                
            }
        }


        public override void Cleanup()
        {
            //base.Cleanup();
        }
    }
}
